<template>
    <div class="community-page">
        <!-- 导航栏 -->
        <van-nav-bar title="Community" fixed>
            <template #right>
                <van-icon name="plus" @click="showCreatePost" />
            </template>
        </van-nav-bar>

        <!-- 顶部标签栏 -->
        <div class="tabs-section">
            <van-tabs v-model:active="activeTab" @change="handleTabChange" sticky>
                <van-tab title="Feed" name="feed" />
                <van-tab title="Achievements" name="achievements" />
                <van-tab title="Leaderboard" name="leaderboard" />
                <van-tab title="Groups" name="groups" />
            </van-tabs>
        </div>

        <!-- 内容区域 -->
        <div class="content-section">
            <!-- 动态流 -->
            <div v-if="activeTab === 'feed'" class="feed-content">
                <!-- 快速发布 -->
                <div class="quick-post-card" @click="showCreatePost">
                    <div class="user-avatar">
                        <van-image :src="currentUser?.avatar || '/default-avatar.png'" width="40" height="40" round
                            fit="cover" />
                    </div>
                    <div class="post-input">
                        <span class="placeholder">Share your training progress...</span>
                    </div>
                    <van-icon name="photo-o" class="media-icon" />
                </div>

                <!-- 动态列表 -->
                <div class="posts-list">
                    <van-loading v-if="loading" size="24px" vertical>Loading posts...</van-loading>
                    <div v-else-if="posts.length > 0">
                        <PostCard v-for="post in posts" :key="post.id" :post="post" @like="handleLike"
                            @comment="handleComment" @share="handleShare" />
                    </div>
                    <van-empty v-else description="No posts yet" image="network">
                        <van-button type="primary" @click="showCreatePost">
                            Create First Post
                        </van-button>
                    </van-empty>
                </div>
            </div>

            <!-- 成就展示 -->
            <div v-if="activeTab === 'achievements'" class="achievements-content">
                <AchievementsGrid :achievements="achievements" />
            </div>

            <!-- 排行榜 -->
            <div v-if="activeTab === 'leaderboard'" class="leaderboard-content">
                <LeaderboardList :leaderboard="leaderboard" />
            </div>

            <!-- 群组 -->
            <div v-if="activeTab === 'groups'" class="groups-content">
                <GroupsList :groups="groups" />
            </div>
        </div>

        <!-- 发布动态弹窗 -->
        <van-popup v-model:show="showCreatePostPopup" position="bottom" :style="{ height: '80%' }" round>
            <CreatePostModal v-if="showCreatePostPopup" @submit="handleCreatePost"
                @close="showCreatePostPopup = false" />
        </van-popup>

        <!-- 评论弹窗 -->
        <van-popup v-model:show="showCommentPopup" position="bottom" :style="{ height: '70%' }" round>
            <CommentsModal v-if="showCommentPopup && selectedPost" :post="selectedPost"
                @close="showCommentPopup = false" />
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showToast } from 'vant'
import { communityApi, type CommunityPost, type Achievement, type User, type CommunityGroup } from '@/api'
import type { LeaderboardUser } from '@/types/user'
import PostCard from '@/components/PostCard.vue'
import CreatePostModal from '@/components/CreatePostModal.vue'
import CommentsModal from '@/components/CommentsModal.vue'
import AchievementsGrid from '@/components/AchievementsGrid.vue'
import LeaderboardList from '@/components/LeaderboardList.vue'
import GroupsList from '@/components/GroupsList.vue'

// 响应式数据
const activeTab = ref('feed')
const loading = ref(true)
const posts = ref<CommunityPost[]>([])
const achievements = ref<Achievement[]>([])
const leaderboard = ref<LeaderboardUser[]>([])
const groups = ref<CommunityGroup[]>([])
const currentUser = ref<User | null>(null)

// 弹窗状态
const showCreatePostPopup = ref(false)
const showCommentPopup = ref(false)
const selectedPost = ref<CommunityPost | null>(null)

// 模拟数据
const initializeMockData = () => {
    // 模拟动态数据
    posts.value = [
        {
            id: 1,
            user: {
                id: 1,
                username: 'Alice Johnson',
                avatar: '/avatar1.png'
            },
            content: 'Just completed my first negotiation training session! The AI coach was incredibly helpful in identifying my weak points. Feeling more confident already! 💪',
            training_result: {
                scenario_name: 'Salary Negotiation',
                score: 8.5,
                duration: 25
            },
            images: ['/training-result1.png'],
            tags: ['negotiation', 'career-growth'],
            likes_count: 24,
            comments_count: 8,
            shares_count: 3,
            is_liked: false,
            created_at: '2024-10-21T10:30:00Z',
            latest_comments: [
                {
                    id: 1,
                    user: { id: 2, username: 'Bob Smith' },
                    content: 'Great job! Which techniques worked best for you?',
                    created_at: '2024-10-21T11:00:00Z'
                }
            ]
        } as CommunityPost,
        {
            id: 2,
            user: {
                id: 2,
                username: 'David Chen',
                avatar: '/avatar2.png'
            },
            content: 'Sharing my weekly progress! Consistency is key in building communication skills. The daily practice sessions are really paying off.',
            images: ['/progress-chart.png', '/weekly-stats.png'],
            tags: ['progress', 'consistency'],
            likes_count: 18,
            comments_count: 5,
            shares_count: 2,
            is_liked: true,
            created_at: '2024-10-21T09:15:00Z'
        } as CommunityPost
    ]

    // 模拟成就数据
    achievements.value = [
        {
            id: 1,
            title: 'First Steps',
            description: 'Complete your first training session',
            icon_url: '/achievement-first-steps.png',
            points: 100,
            is_unlocked: true,
            is_featured: false,
            unlocked_at: '2024-10-20T14:30:00Z'
        } as Achievement,
        {
            id: 2,
            title: 'Communication Master',
            description: 'Achieve an average score of 8+ in communication scenarios',
            icon_url: '/achievement-communication.png',
            points: 500,
            is_unlocked: false,
            is_featured: true,
            progress: {
                current: 6,
                target: 10
            },
            requirements: [
                'Complete 10 communication training sessions',
                'Maintain an average score of 8 or higher',
                'Receive positive feedback from 5 different scenarios'
            ]
        } as Achievement,
        {
            id: 3,
            title: 'Team Player',
            description: 'Successfully complete 5 team collaboration scenarios',
            icon_url: '/achievement-team.png',
            points: 300,
            is_unlocked: true,
            is_featured: false,
            unlocked_at: '2024-10-19T16:45:00Z'
        } as Achievement
    ]

    // 模拟排行榜数据
    leaderboard.value = [
        {
            id: 1,
            username: 'Sarah Wilson',
            email: 'sarah@example.com',
            avatar: '/avatar-sarah.png',
            tier: 'Expert',
            level: 15,
            experiencePoints: 12500,
            isEmailVerified: true,
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-10-21T00:00:00Z',
            score: 12500,
            is_online: true,
            rank_change: 2
        } as LeaderboardUser,
        {
            id: 2,
            username: 'Mike Johnson',
            email: 'mike@example.com',
            avatar: '/avatar-mike.png',
            tier: 'Advanced',
            level: 14,
            experiencePoints: 11800,
            isEmailVerified: true,
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-10-21T00:00:00Z',
            score: 11800,
            is_online: false,
            rank_change: -1
        } as LeaderboardUser,
        {
            id: 3,
            username: 'Emma Davis',
            email: 'emma@example.com',
            avatar: '/avatar-emma.png',
            tier: 'Advanced',
            level: 13,
            experiencePoints: 10900,
            isEmailVerified: true,
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-10-21T00:00:00Z',
            score: 10900,
            is_online: true,
            rank_change: 0
        } as LeaderboardUser,
        {
            id: 4,
            username: 'Alex Chen',
            email: 'alex@example.com',
            avatar: '/avatar-alex.png',
            tier: 'Intermediate',
            level: 12,
            experiencePoints: 9750,
            isEmailVerified: true,
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-10-21T00:00:00Z',
            score: 9750,
            is_online: true,
            rank_change: 3,
            is_current_user: false
        } as LeaderboardUser,
        {
            id: 5,
            username: 'Lisa Brown',
            email: 'lisa@example.com',
            avatar: '/avatar-lisa.png',
            tier: 'Intermediate',
            level: 11,
            experiencePoints: 8900,
            isEmailVerified: true,
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-10-21T00:00:00Z',
            score: 8900,
            is_online: false,
            rank_change: -2
        } as LeaderboardUser
    ]

    // 模拟群组数据
    groups.value = [
        {
            id: 1,
            name: 'Communication Skills Hub',
            description: 'A community for improving communication and interpersonal skills',
            avatar: '/group-communication.png',
            members_count: 1250,
            posts_count: 450,
            activity_level: 'High',
            is_joined: true,
            is_private: false,
            is_verified: true,
            tags: ['communication', 'networking', 'career'],
            latest_activity: {
                text: 'New post by Sarah Wilson',
                time: '2024-10-21T12:00:00Z'
            },
            created_at: '2024-09-15T10:00:00Z'
        } as CommunityGroup,
        {
            id: 2,
            name: 'Leadership Development',
            description: 'Develop your leadership skills through practice and feedback',
            avatar: '/group-leadership.png',
            members_count: 890,
            posts_count: 320,
            activity_level: 'Medium',
            is_joined: false,
            is_private: false,
            is_verified: true,
            tags: ['leadership', 'management', 'growth'],
            latest_activity: {
                text: 'Weekly challenge posted',
                time: '2024-10-21T08:30:00Z'
            },
            created_at: '2024-09-10T14:00:00Z'
        } as CommunityGroup,
        {
            id: 3,
            name: 'Negotiation Masters',
            description: 'Master the art of negotiation in business and personal contexts',
            avatar: '/group-negotiation.png',
            members_count: 650,
            posts_count: 280,
            activity_level: 'High',
            is_joined: false,
            is_private: true,
            is_verified: false,
            tags: ['negotiation', 'business', 'strategy'],
            latest_activity: {
                text: 'Case study discussion',
                time: '2024-10-20T16:45:00Z'
            },
            created_at: '2024-09-20T09:00:00Z'
        } as CommunityGroup
    ]

    // 模拟当前用户
    currentUser.value = {
        id: 100,
        username: 'You',
        avatar: '/default-avatar.png',
        level: 8
    } as User
}

// 方法
const loadFeedData = async () => {
    try {
        loading.value = true
        // 在实际应用中，这里会调用API
        // const response = await communityApi.getPosts()
        // posts.value = response.data

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
    } catch (error) {
        console.error('Failed to load posts:', error)
        showToast('Failed to load posts')
    } finally {
        loading.value = false
    }
}

const loadAchievements = async () => {
    try {
        // const response = await communityApi.getAchievements()
        // achievements.value = response.data
    } catch (error) {
        console.error('Failed to load achievements:', error)
    }
}

const loadLeaderboard = async () => {
    try {
        // const response = await communityApi.getLeaderboard()
        // leaderboard.value = response.data
    } catch (error) {
        console.error('Failed to load leaderboard:', error)
    }
}

const loadGroups = async () => {
    try {
        // const response = await communityApi.getGroups()
        // groups.value = response.data
    } catch (error) {
        console.error('Failed to load groups:', error)
    }
}

const handleTabChange = (name: string) => {
    switch (name) {
        case 'feed':
            if (posts.value.length === 0) {
                loadFeedData()
            }
            break
        case 'achievements':
            if (achievements.value.length === 0) {
                loadAchievements()
            }
            break
        case 'leaderboard':
            if (leaderboard.value.length === 0) {
                loadLeaderboard()
            }
            break
        case 'groups':
            if (groups.value.length === 0) {
                loadGroups()
            }
            break
    }
}

const showCreatePost = () => {
    showCreatePostPopup.value = true
}

const handleCreatePost = async (postData: any) => {
    try {
        // const response = await communityApi.createPost(postData)
        // posts.value.unshift(response.data)

        // 模拟创建动态
        const newPost: CommunityPost = {
            id: Date.now(),
            user: {
                id: currentUser.value!.id,
                username: currentUser.value!.username,
                avatar: currentUser.value!.avatar
            },
            content: postData.content,
            training_result: postData.training_result,
            images: postData.images,
            tags: postData.tags,
            likes_count: 0,
            comments_count: 0,
            shares_count: 0,
            is_liked: false,
            created_at: new Date().toISOString()
        }

        posts.value.unshift(newPost)
        showCreatePostPopup.value = false
        showToast('Post created successfully!')
    } catch (error) {
        console.error('Failed to create post:', error)
        showToast('Failed to create post')
    }
}

const handleLike = async (post: CommunityPost) => {
    try {
        if (post.is_liked) {
            // await communityApi.unlikePost(post.id)
            post.is_liked = false
            post.likes_count = (post.likes_count || 0) - 1
        } else {
            // await communityApi.likePost(post.id)
            post.is_liked = true
            post.likes_count = (post.likes_count || 0) + 1
        }
    } catch (error) {
        console.error('Failed to toggle like:', error)
        showToast('Failed to update like')
    }
}

const handleComment = (post: CommunityPost) => {
    selectedPost.value = post
    showCommentPopup.value = true
}

const handleShare = async (post: CommunityPost) => {
    try {
        // 实现分享功能
        if (navigator.share) {
            await navigator.share({
                title: 'Check out this post',
                text: post.content,
                url: window.location.href
            })
        } else {
            // 备用分享方案
            await navigator.clipboard.writeText(window.location.href)
            showToast('Link copied to clipboard')
        }
    } catch (error) {
        console.error('Failed to share:', error)
        showToast('Failed to share post')
    }
}

// 生命周期
onMounted(() => {
    initializeMockData()
    loadFeedData()
})
</script>

<style lang="scss" scoped>
.community-page {
    min-height: 100vh;
    background: #f7f8fa;
    padding-top: 46px; // 导航栏高度

    .tabs-section {
        background: white;
        border-bottom: 1px solid #ebedf0;
    }

    .content-section {
        padding: 16px;

        .feed-content {
            .quick-post-card {
                background: white;
                border-radius: 12px;
                padding: 16px;
                margin-bottom: 16px;
                display: flex;
                align-items: center;
                gap: 12px;
                cursor: pointer;
                transition: all 0.3s ease;

                &:hover {
                    transform: translateY(-1px);
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                }

                .user-avatar {
                    flex-shrink: 0;
                }

                .post-input {
                    flex: 1;

                    .placeholder {
                        color: #969799;
                        font-size: 16px;
                    }
                }

                .media-icon {
                    color: #1989fa;
                    font-size: 20px;
                }
            }

            .posts-list {
                display: flex;
                flex-direction: column;
                gap: 16px;
            }
        }

        .achievements-content,
        .leaderboard-content,
        .groups-content {
            background: white;
            border-radius: 12px;
            padding: 16px;
        }
    }
}
</style>